package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"short-video-dev/cache"
	"short-video-dev/mysql"
	"short-video-dev/pkg"
	"strconv"

	"short-video-dev/videorpc/internal/svc"
	"short-video-dev/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginOrRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginOrRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginOrRegisterLogic {
	return &LoginOrRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录注册
func (l *LoginOrRegisterLogic) LoginOrRegister(in *videorpc.LoginOrRegisterRequest) (*videorpc.LoginOrRegisterResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.UserInfo
	err := user.FindUserByMobile(mysql.DB, in.Mobile)
	if err != nil {
		return nil, err
	}

	smsKey := fmt.Sprintf("sms_%v", in.Mobile)

	if in.TypeId == 1 { //密码登录

		if user.ID == 0 {
			return nil, errors.New("用户不存在,请先注册")
		}
		if pkg.Md5(in.Password) != user.Pwd {
			return nil, errors.New("密码错误,请重新输入密码")
		}
	} else if in.TypeId == 2 { //验证码登录
		if user.ID == 0 {
			return nil, errors.New("用户不存在,请先注册")
		}

		if in.SmsCode == "" {
			return nil, errors.New("请输入验证码")
		}
		sms, _ := cache.Rdb.Get(l.ctx, smsKey).Result()
		if sms == "" {
			return nil, errors.New("验证码已过期，请重新获取")
		}
		if sms != in.SmsCode {
			return nil, errors.New("验证码错误,请重新输入")
		}

	} else if in.TypeId == 3 { //注册

		if user.ID != 0 {
			return nil, errors.New("该手机号已注册,可以直接登录")
		}

		if in.SmsCode == "" {
			return nil, errors.New("请输入验证码")
		}
		sms, _ := cache.Rdb.Get(l.ctx, smsKey).Result()
		if sms == "" {
			return nil, errors.New("验证码已过期，请重新获取")
		}
		if sms != in.SmsCode {
			return nil, errors.New("验证码错误,请重新输入")
		}

		user = mysql.UserInfo{
			PhoneNum:      in.Mobile,
			Pwd:           pkg.Md5(in.Password),
			NikeName:      fmt.Sprintf("用户_%v", rand.Intn(89089890890)),
			AvatarLink:    "http://t4k9mwqth.hn-bkt.clouddn.com/OIP-C.webp",
			AccountStatus: 0,
			FollowNum:     0,
			FansNum:       0,
		}
		err := user.Register(mysql.DB)
		if err != nil {
			return nil, errors.New("注册失败")
		}
	} else {
		return nil, errors.New("请选择登录方式")
	}

	err = user.FindUserByMobile(mysql.DB, in.Mobile)
	if err != nil {
		return nil, err
	}
	if user.AccountStatus == 1 {
		return nil, errors.New("此账号正在禁用中")
	}

	handler, err := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	if err != nil {
		return nil, errors.New("登录失败")
	}
	return &videorpc.LoginOrRegisterResponse{
		Token: handler,
	}, nil
}
